package com.hirsi.core;

import com.hirsi.common.core.enums.DataStatusEnum;
import com.hirsi.common.core.enums.ExceptionStatusEnum;
import com.hirsi.common.core.exception.ServerRuntimeException;
import com.hirsi.common.core.util.EncryptUtil;
import com.hirsi.common.db.manager.entity.Manager;
import com.hirsi.common.db.manager.service.IManagerService;
import com.hirsi.common.module.auth.service.IAuthUserService;
import com.hirsi.common.module.auth.vo.param.IAuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ManagerAuthServiceImpl implements IAuthUserService {

    @Autowired
    private IManagerService managerService;

    @Override
    public IAuthUser getUserByAccount(String account) {
        Manager manager = managerService.lambdaQuery()
                .eq(Manager::getUsername, account)
                .or().eq(Manager::getPhone, EncryptUtil.encrypt(account))
                .select(Manager::getId, Manager::getPassword, Manager::getStatus)
                .last("limit 1").one();
        if (manager != null && !DataStatusEnum.ENABLE.getValue().equals(manager.getStatus())) {
            throw new ServerRuntimeException(ExceptionStatusEnum.USER_STATUS_EXCEPTION);
        }
        return manager;
    }

    @Override
    public Boolean checkPhone(String phone) {
        Manager manager = managerService.lambdaQuery()
                .eq(Manager::getPhone, EncryptUtil.encrypt(phone))
                .select(Manager::getStatus)
                .last("limit 1").one();
        if (manager == null) return false;
        else if (!DataStatusEnum.ENABLE.getValue().equals(manager.getStatus())) {
            throw new ServerRuntimeException(ExceptionStatusEnum.USER_STATUS_EXCEPTION);
        }
        return true;
    }

    @Override
    public IAuthUser getUserByPhone(String phone) {
        Manager manager = managerService.lambdaQuery()
                .eq(Manager::getPhone, EncryptUtil.encrypt(phone))
                .select(Manager::getId, Manager::getStatus)
                .last("limit 1").one();
        if (manager != null && !DataStatusEnum.ENABLE.getValue().equals(manager.getStatus())) {
            throw new ServerRuntimeException(ExceptionStatusEnum.USER_STATUS_EXCEPTION);
        }
        return manager;
    }
}
